import React, {Component} from 'react';
import {Form, Input, Button, message} from 'antd';
import {UserOutlined, LockOutlined} from '@ant-design/icons';
import {connect} from 'react-redux'
import './index.less'
import logo from '../../assets/images/logo.png'
import {reqLogin} from '../../api'
import {saveUserAndToken} from '../../redux/actions/login'
import {Redirect} from "react-router-dom";


/**
 * 用户登录的路由组件
 */
class Login extends Component {

    /**
     * 提交表单且数据验证成功后回调事件
     * @param values
     */
    handleFinish = async (values) => {
        const {username, password} = values;
        let result = await reqLogin(username, password);
        const {status, msg, data} = result;
        if (status === 0) {
            //服务器返回的user信息和token信交由redux管理
            const {user, token} = data;
            this.props.saveUserAndToken({user, token});
            //提示登录成功
            message.info("登录成功", 2);
            //跳转到admin页面
            this.props.history.replace("/admin/home");
        } else {
            message.warn(msg, 2);
        }
    }

    /**
     * 提交表单且数据验证失败后回调事件
     */
    handleFinishFailed = (errorInfo) => {
      
        console.log('@', errorInfo)
    }

    render() {
        const {isLogin} = this.props;
        if (isLogin) { //如果是已经登录状态，直接跳转到Admin界面
            //跳转到登录页面
            return <Redirect to="/admin"/>
        }

        return (
            <div className="login">
                <header className="login-header">
                    <img src={logo} alt="logo"/>
                    <h1>React项目：后台管理系统</h1>
                </header>
                <section className="login-content">
                    <h2>用户登录</h2>
                    {/*
                        onFinish：统一校验，提交表单且数据验证成功后回调事件
                        onFinishFailed：统一校验，提交表单且数据验证失败后回调事件
                    */}
                    <Form onFinish={this.handleFinish} onFinishFailed={this.handleFinishFailed} className="login-form">
                        {/*
                            Form的声明式验证：直接使用别人定义好的验证规则进行验证。
                        */}
                        <Form.Item name="username" rules={[
                            {required: true, whitespace: true, message: '请输入用户名!'},
                            {min: 4, message: '用户名必须大于4位'},
                            {max: 12, message: '用户名必须小于12位'},
                            {pattern: /^[a-zA-Z0-9_]+$/, message: '用户名必须是英文、数字或下划线组成'}
                        ]} initialValue={"admin"}>
                            <Input prefix={<UserOutlined className="site-form-item-icon"/>} placeholder="用户名"
                                   autoComplete="off"/>
                        </Form.Item>
                        {/* Form的自定义验证 */}
                        <Form.Item name="password" rules={[
                            {
                                validator: async (rule, value) => {
                                    if (!value) {
                                        throw new Error('请输入密码!');
                                    }
                                    if (value.length < 4) {
                                        throw new Error('密码必须大于4位');
                                    }
                                    if (value.length > 12) {
                                        throw new Error('用户名必须小于12位');
                                    }
                                    if (!(/^[a-zA-Z0-9_]+$/.test(value))) {
                                        throw new Error('密码必须是英文、数组或下划线组成');
                                    }
                                }
                            }
                        ]}>
                            <Input prefix={<LockOutlined className="site-form-item-icon"/>} type="password"
                                   placeholder="密码" autoComplete="off"/>
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" className="login-form-button">
                                登录
                            </Button>
                        </Form.Item>
                    </Form>
                </section>
            </div>
        );
    }
}


export default connect(
    state => ({isLogin: state.login.isLogin}),
    {
        saveUserAndToken
    }
)(Login)

